import http from "@/utils/http"
import * as types from "../actionType"

export const setChannels = (payload) => ({ type: types.SET_CHANNELS, payload })

export const setArticles = (payload) => ({ type: types.SET_ARTICLES, payload })

export const getChannels = () => {
  return async (dispatch) => {
    // 获取频道数据
    const {
      data: { channels },
    } = await http.get("/v1_0/channels")
    dispatch(setChannels(channels)) // 派发频道数据到 reducer
  }
}

export const getArticles = (params) => {
  return async (dispatch) => {
    // axios 地址参数 params  请求体参数 data
    const { data } = await http.get("/v1_0/mp/articles", {
      params,
    })
    dispatch(setArticles(data)) // data就是要派发的数据
  }
}
export const delArticle = (id) => {
  return async (dispatch) => {
    await http.delete(`/v1_0/mp/articles/${id}`) // 删除文章
    // 可以直接移除前端数据- 做一些其他的redux操作
  }
}

export const addArticle = (data, draft = false) => {
  return async (dispatch) => {
    await http.post(`/v1_0/mp/articles?draft=${draft}`, data)
  }
}

export const editArticle = (data, draft = false) => {
  return async (dispatch) => {
    await http.put(`/v1_0/mp/articles/${data.id}?draft=${draft}`, data)
  }
}

export const getArticle = (id) => {
  return async (dispatch) => {
    const data = await http.get("/v1_0/mp/articles/" + id)
    return data
  }
}
